<?php

namespace App\Http\Middleware;

use Closure;
use App\Model\User;
use App\Model\Role;
use App\Model\Permission;

class HasPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        Role::get();
        Permission::get();
        //1.获取当前请求的路由  对应的控制器方法名
        //"App\Http\Controllers\Admin\RegisterController@index"
        $route = \Route::current()->getActionName();
        //dd($route);
        //判断当前请求路由是否在用户存储的session中
        $per = session()->get('permission');
        if(in_array($route,$per)){
            return $next($request);
        }else{
            //2.获取当前用户拥有的权限组
            $user = User::find(session()->get('user')->user_id);

            //获取当前用户拥有的角色
            $roles = $user->role;
            //存放所有权限
            $arr = [];
            //根据用户拥有的角色，找对应的权限
            foreach ($roles as $per){
                foreach ($per->permission as $v){
                    $arr[] = $v->per_url;
                }
            }

            //去掉重复的权限
            $arr = array_unique($arr);
            //dd($arr);

            //判断当前请求的路由对应的控制器的方法名是否在当前用户拥有的权限中
            if(in_array($route,$arr)){
                return $next($request);
            }else{
                return redirect("noaccess");
            }
        }
    }
}
